import {
  login,
  logout,
  getInfo
} from '@/api/user'
import { 
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  async login({
    commit
  }, {
    username,
    password
  }) {
    try {
      const {
        data
      } = await login({
        username,
        password
      })
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      return data
    } catch (e) {
      return Promise.reject(e)
    }
  },

  // get user info
  async getInfo({
    commit,
    state
  }) {
    try {
      const {
        data
      } = await getInfo(state.token)
      if (!data) return Promise.reject('Verification failed, please Login again.')
      const {
        name,
        avatar
      } = data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      return data
    } catch (e) {
      return Promise.reject(e)
    }
  },

  // user logout
  async logout({
    commit,
    state
  }) {
    try {
      await logout(state.token)
      removeToken()
      resetRouter()
      commit('RESET_STATE')
    } catch (e) {
      return Promise.reject(e)
    }

  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
